'use client'

import React, { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import * as echarts from 'echarts'

interface EnergyData {
  date: string
  tee: number
  bmr: number
  tef: number
  eepa: number
}

interface WeeklyTarget {
  target_tee: number
  goal: string
}

interface EnergyConsumptionChartProps {
  userId: string
  selectedDate: string
}

export function EnergyConsumptionChart({ userId, selectedDate }: EnergyConsumptionChartProps) {
  const [weeklyData, setWeeklyData] = useState<EnergyData[]>([])
  const [weeklyTarget, setWeeklyTarget] = useState<WeeklyTarget | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  // 获取近一周的日期范围
  const getWeekDates = (endDate: string) => {
    const dates = []
    const end = new Date(endDate)
    
    for (let i = 6; i >= 0; i--) {
      const date = new Date(end)
      date.setDate(date.getDate() - i)
      dates.push(date.toISOString().split('T')[0])
    }
    
    return dates
  }

  // 获取一周的能量消耗数据
  const fetchWeeklyEnergyData = async () => {
    try {
      setLoading(true)
      setError(null)

      const dates = getWeekDates(selectedDate)
      const energyPromises = dates.map(date => 
        fetch(`/api/health/daily-energy?userId=${userId}&date=${date}`)
          .then(res => res.json())
          .then(data => ({ date, ...data.data }))
          .catch(err => ({ date, error: err.message }))
      )

      // 获取每周目标
      const targetResponse = await fetch(`/api/health/weekly-energy-target?userId=${userId}&date=${selectedDate}&goal=lose&rate=0.5`)
      const targetData = await targetResponse.json()

      const energyResults = await Promise.all(energyPromises)
      const validData = energyResults.filter(item => !item.error && item.tee)

      setWeeklyData(validData)
      setWeeklyTarget(targetData.data)
      
    } catch (err) {
      console.error('获取能量消耗数据失败:', err)
      setError('获取数据失败')
    } finally {
      setLoading(false)
    }
  }

  // 生成图表
  const generateEnergyChart = () => {
    const chartDom = document.getElementById('energy-consumption-chart')
    if (!chartDom || weeklyData.length === 0) return

    const myChart = echarts.init(chartDom)

    // 准备数据
    const dates = weeklyData.map(item => {
      const date = new Date(item.date)
      return `${date.getMonth() + 1}/${date.getDate()}`
    })

    const teeData = weeklyData.map(item => item.tee)
    const bmrData = weeklyData.map(item => item.bmr)
    const eepaData = weeklyData.map(item => item.eepa)
    const tefData = weeklyData.map(item => item.tef)

    // 目标线数据
    const targetLine = weeklyTarget ? Array(dates.length).fill(weeklyTarget.target_tee) : []

    const option = {
      title: {
        text: '近一周能量消耗趋势',
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        },
        formatter: function(params: any) {
          let result = `<div style="font-weight: bold; margin-bottom: 8px;">${params[0].axisValue}</div>`
          
          params.forEach((param: any) => {
            const color = param.color
            const seriesName = param.seriesName
            const value = param.value
            
            if (seriesName === '目标TEE') {
              result += `<div style="margin: 4px 0;">
                <span style="display: inline-block; width: 10px; height: 10px; background: ${color}; margin-right: 8px; border-radius: 2px;"></span>
                ${seriesName}: ${value} kcal
              </div>`
            } else {
              result += `<div style="margin: 4px 0;">
                <span style="display: inline-block; width: 10px; height: 10px; background: ${color}; margin-right: 8px;"></span>
                ${seriesName}: ${value} kcal
              </div>`
            }
          })
          
          return result
        }
      },
      legend: {
        data: ['总能量消耗(TEE)', '基础代谢(BMR)', '体力活动(EEPA)', '食物热效应(TEF)', '目标TEE'],
        top: 30,
        textStyle: {
          fontSize: 12
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: dates,
        axisLabel: {
          fontSize: 11
        }
      },
      yAxis: {
        type: 'value',
        name: '能量 (kcal)',
        nameTextStyle: {
          fontSize: 12
        },
        axisLabel: {
          fontSize: 11,
          formatter: '{value}'
        }
      },
      series: [
        {
          name: '总能量消耗(TEE)',
          type: 'line',
          data: teeData,
          lineStyle: {
            color: '#2563eb',
            width: 3
          },
          itemStyle: {
            color: '#2563eb'
          },
          symbol: 'none',
          emphasis: {
            focus: 'series',
            lineStyle: {
              width: 4
            }
          },
          smooth: true
        },
        {
          name: '基础代谢(BMR)',
          type: 'line',
          data: bmrData,
          lineStyle: {
            color: '#059669',
            width: 2
          },
          itemStyle: {
            color: '#059669'
          },
          symbol: 'none',
          emphasis: {
            focus: 'series',
            lineStyle: {
              width: 3
            }
          },
          smooth: true
        },
        {
          name: '体力活动(EEPA)',
          type: 'line',
          data: eepaData,
          lineStyle: {
            color: '#d97706',
            width: 2
          },
          itemStyle: {
            color: '#d97706'
          },
          symbol: 'none',
          emphasis: {
            focus: 'series',
            lineStyle: {
              width: 3
            }
          },
          smooth: true
        },
        {
          name: '食物热效应(TEF)',
          type: 'line',
          data: tefData,
          lineStyle: {
            color: '#7c3aed',
            width: 2
          },
          itemStyle: {
            color: '#7c3aed'
          },
          symbol: 'none',
          emphasis: {
            focus: 'series',
            lineStyle: {
              width: 3
            }
          },
          smooth: true
        },
        ...(weeklyTarget ? [{
          name: '目标TEE',
          type: 'line',
          data: targetLine,
          lineStyle: {
            color: '#dc2626',
            width: 2,
            type: 'dashed'
          },
          itemStyle: {
            color: '#dc2626'
          },
          symbol: 'none',
          emphasis: {
            focus: 'series',
            lineStyle: {
              width: 3
            }
          },
          markLine: {
            silent: true,
            data: [{
              yAxis: weeklyTarget.target_tee,
              lineStyle: {
                color: '#dc2626',
                type: 'dashed',
                width: 1
              },
              label: {
                formatter: '目标: {c} kcal',
                position: 'end'
              }
            }]
          }
        }] : [])
      ]
    }

    myChart.setOption(option)

    // 响应式调整
    const resizeChart = () => {
      myChart.resize()
    }
    window.addEventListener('resize', resizeChart)

    return () => {
      window.removeEventListener('resize', resizeChart)
      myChart.dispose()
    }
  }

  // 获取统计信息
  const getStatistics = () => {
    if (weeklyData.length === 0) return []

    const avgTEE = weeklyData.reduce((sum, item) => sum + item.tee, 0) / weeklyData.length
    const maxTEE = Math.max(...weeklyData.map(item => item.tee))
    const minTEE = Math.min(...weeklyData.map(item => item.tee))
    const avgEEPA = weeklyData.reduce((sum, item) => sum + item.eepa, 0) / weeklyData.length

    const stats = [
      { label: '平均TEE', value: `${avgTEE.toFixed(0)} kcal`, color: 'text-blue-600' },
      { label: '最高TEE', value: `${maxTEE.toFixed(0)} kcal`, color: 'text-green-600' },
      { label: '最低TEE', value: `${minTEE.toFixed(0)} kcal`, color: 'text-orange-600' },
      { label: '平均EEPA', value: `${avgEEPA.toFixed(0)} kcal`, color: 'text-purple-600' }
    ]

    if (weeklyTarget) {
      const targetDiff = avgTEE - weeklyTarget.target_tee
      const diffColor = targetDiff > 0 ? 'text-red-600' : 'text-green-600'
      const diffSign = targetDiff > 0 ? '+' : ''
      stats.push({
        label: '与目标差异',
        value: `${diffSign}${targetDiff.toFixed(0)} kcal`,
        color: diffColor
      })
    }

    return stats
  }

  useEffect(() => {
    fetchWeeklyEnergyData()
  }, [userId, selectedDate])

  useEffect(() => {
    if (!loading && weeklyData.length > 0) {
      const cleanup = generateEnergyChart()
      return cleanup
    }
  }, [weeklyData, weeklyTarget, loading])

  if (loading) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>近一周能量消耗</CardTitle>
          <CardDescription>加载中...</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="h-64 flex items-center justify-center">
            <div className="text-gray-500">正在加载数据...</div>
          </div>
        </CardContent>
      </Card>
    )
  }

  if (error) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>近一周能量消耗</CardTitle>
          <CardDescription className="text-red-500">{error}</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="h-64 flex items-center justify-center">
            <div className="text-red-500">数据加载失败</div>
          </div>
        </CardContent>
      </Card>
    )
  }

  const statistics = getStatistics()

  return (
    <Card>
      <CardHeader>
        <CardTitle>近一周能量消耗</CardTitle>
        <CardDescription>
          显示近7天的总能量消耗(TEE)、基础代谢(BMR)、体力活动消耗(EEPA)和食物热效应(TEF)趋势。
          红色虚线为减重目标的理想TEE水平。
        </CardDescription>
      </CardHeader>
      <CardContent>
        <div id="energy-consumption-chart" style={{ width: '100%', height: '400px' }}></div>
        
        {statistics.length > 0 && (
          <div className="mt-6">
            <h4 className="text-sm font-medium text-gray-700 mb-3">一周统计</h4>
            <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4">
              {statistics.map((stat, index) => (
                <div key={index} className="text-center">
                  <div className="text-xs text-gray-500 mb-1">{stat.label}</div>
                  <div className={`text-sm font-medium ${stat.color}`}>{stat.value}</div>
                </div>
              ))}
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  )
}
